﻿//Global variables for music and playlist operations
var visibilityArtist = false;
var prevArtistId;
var visibilityLyrics = false;
var prevLyricsId;
var dataDisplayPhrase = "";
var defaultSorting = "songName";
var selected = "songName";
$(document).ready(function () {
    //getSongs(selected, dataDisplayPhrase,true);
    
    // Click event handler for requesting the playlist list
    $("#myPlaylist").click(function () {
        $("#errorMessages").fadeOut("slow").empty();
        getPlaylists();
    });

    // Click event handler for searching by filter, keywords or string
    $("#searchButton").click(function () {
        $("#errorMessages").fadeOut("slow").empty();
        dataDisplayPhrase = $("#searchValue").val();
        getSongs(defaultSorting, dataDisplayPhrase, true);
        $("#searchButton").attr("href", "#/search/" + dataDisplayPhrase);
        $("#searchValue").val("");
    });

    // Click event handler for loading a playlist from playlist list
    $(".play").live("click", function(){
        $("#errorMessages").fadeOut("slow").empty();
        var songId = $(this).attr("id");
        var id = songId.match(/\d+$/);

        playSongsFromPlaylist(id);
    });

    // Click event handler for adding a song to a playlist
    $(".addToPlaylist").live("click", function () {
        $("#errorMessages").fadeOut("slow").empty();
        var songId = $(this).attr("id");
        var id = songId.match(/\d+$/);
        appendDropDownList(id);
        $("#addSong-" + id).fadeOut("fast");        
    });

    // Click event handler for removing/deleting a playlist
    $(".removePlaylist").live("click", function (){
        $("#errorMessages").fadeOut("slow").empty();
        var songId = $(this).attr("id");
        var id = songId.match(/\d+$/);

        removeFromPlaylist(id);
    });

    // Click event handler for adding a song to a playlist
    $(".playlistDropDown").live("change", function(){
        $("#errorMessages").fadeOut("slow").empty();
        var songId = $(this).attr("id");
        var id = songId.match(/\d+$/);
        var playlistId = $(this).find("option:selected").val();

        if(playlistId != ""){
            addSongToPlayList(id, playlistId);
        }     
        $("#playListDropDown-"  + id).remove();
        $("#addSong-" + id).fadeIn("fast");
    });

    // Click event handler for removing a song from collection
    $(".removeSong").live("click", function () {
        $("#errorMessages").fadeOut("slow").empty();
        var songId = $(this).attr("id");
        var id = songId.match(/\d+$/);
        removeSong(id);
    });

    // Change event handler for sorting content by criteria
    $("#sortSongs").live("change", function () {
        $("#errorMessages").fadeOut("slow").empty();
        selected = $(this).find("option:selected").val();
        getSongs(selected, dataDisplayPhrase, false);
    });

    // Click event handler for getting artist information
    $(".artist").live("click", function () {
        $("#errorMessages").fadeOut("slow").empty();
        var songId = $(this).attr("id");
        var id = "";
        id += songId.match(/\d+$/);
        if (visibilityArtist == true && parseInt(id) == parseInt(prevArtistId)) {
            visibilityArtist = false;
            $('#artistInfo-' + prevArtistId).slideUp("fast").remove();
            prevArtistId = -1;
        }
        else {
            if (visibilityArtist == true) {
                $('#artistInfo-' + prevArtistId).slideUp("fast").remove();
            }
            prevArtistId = id;
            visibilityArtist = true;
            getSongByIdForArtist(id);
        }
    });

    // Click event handler for getting lyrics information
    $(".lyrics").live("click", function () {
        $("#errorMessages").fadeOut("slow").empty();
        var songId = $(this).attr("id");
        var id = "";
        id += songId.match(/\d+$/);
        if (visibilityLyrics == true && parseInt(id) == parseInt(prevLyricsId)) {
            visibilityLyrics = false;
            $('#lyricsInfo-' + prevLyricsId).slideUp("fast").remove();
            prevLyricsId = -1;
        }
        else {
            if (visibilityLyrics == true) {
                $('#lyricsInfo-' + prevLyricsId).slideUp("fast").remove();
            }
            prevLyricsId = id;
            visibilityLyrics = true;
            getSongByIdForLyrics(id);
        }
    });

    // Click event handler for getting all the content(music)
    $("#GetSong").click(function () {  
        $("#errorMessages").fadeOut("slow").empty();    
        getSongs(defaultSorting, "", true);
    });

    // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
    $("#dialog:ui-dialog").dialog("destroy");

    //Variables and helpers functions for file uploading and jquery form 'POP-UP'
    var songSource = $("#data"),
			allFields = $([]).add(songSource),
			tips = $(".validateTips");
    function updateTips(t) {
        tips
				.text(t)
				.addClass("ui-state-highlight");
        setTimeout(function () {
            tips.removeClass("ui-state-highlight", 1500);
        }, 500);
    }
    function checkLength(o, n, min, max) {
        if (o.val().length > max || o.val().length < min) {
            o.addClass("ui-state-error");
            updateTips("Length of " + n + " must be between " +
					min + " and " + max + ".");
            return false;
        } else {
            return true;
        }
    }
    function custom(o, n, min, max) {
        if (o.val().length > max || o.val().length < min) {
            o.addClass("ui-state-error");
            updateTips("Music file is required.");
            return false;
        } else {
            return true;
        }
    }
    function checkRegexp(o, regexp, n) {
        if (!(regexp.test(o.val()))) {
            o.addClass("ui-state-error");
            updateTips(n);
            return false;
        } else {
            return true;
        }
    }

    // JQuery dialog event handler for file uploading form
    $("#dialog-form").dialog({
        autoOpen: false,
        height: 300,
        width: 350,
        modal: true,
        buttons: {
            "Upload Song": function () {
                var bValid = true;
                allFields.removeClass("ui-state-error");

                bValid = bValid && custom(songSource, "song source", 1, 100);
                // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/

                if (bValid) {
                    $("#theForm").submit();
                }
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        },
        close: function () {
            allFields.val("").removeClass("ui-state-error");
            getSongs(defaultSorting, dataDisplayPhrase, true);
        }
    });

    // Click event handler for opening file upload input form
    $("#uploadSong").click(function () {
        $("#dialog-form").dialog("open");
        $("#errorMessages").fadeOut("slow").empty();
    });

    // Helper variables for playlist creation form
    var playlistName = $("#playlistName"),
			allFieldsPlaylist = $([]).add(playlistName),
            tipsPlaylist = $(".validateTipsPlaylist");

    // JQuery dialog event handler for playlist creating form
    $("#dialog-form-playlist").dialog({
        autoOpen: false,
        height: 300,
        width: 350,
        modal: true,
        buttons: {
            "Create Playlist": function () {
                var bValid = true;
                allFieldsPlaylist.removeClass("ui-state-error");

                bValid = bValid && checkLength(playlistName, "playlist name", 1, 50);
                // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/

                if (bValid) {
                    //Add to Playlist and reload playlist: GUDRUN
                    var value = $("#playlistName").val();
                    var request = $.ajax({
                        type: 'POST',
                        dataType: 'json',
                        url: '/api/playlist2/',
                        data: {listName: value}
                    });
                    request.done(function (data) {
                        getPlaylists();
                    });
                    request.fail(function (jqXHR, textStatus) {
                        alert("Request failed(creating playlist): " + textStatus);
                    });
                    $(this).dialog("close");
                }
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        },
        close: function () {
            allFieldsPlaylist.val("").removeClass("ui-state-error");
        }
    });

    // Click event handler for opening playlist creation input form
    $("#createPlaylist").live("click", function () {
        $("#errorMessages").fadeOut("slow").empty();
        $("#dialog-form-playlist").dialog("open");
    });

    // Single app routing functions for bookmarking using Sammy!
    var app = $.sammy('#main', function() {
      
        this.get('#/', function(context) {
            getSongs(selected, dataDisplayPhrase,true);
            context.log('Main page');
        });

        this.get('#/playlist/', function(context) {
            context.log('Getting playlist');
            getPlaylists();
        });

        this.get('#/playlist/:id', function(context) {
            var id = this.params['id'];
            context.log('Getting playlist with id ' + id);
            getPlaylists();
            playSongsFromPlaylist(id);
        });

//        this.get('#/playlist/addplaylist', function(context) {
//            context.log('Add playlist');
//            $("#dialog-form-playlist").dialog("open");
//        });

//        this.get('#/playlist/removeplaylist/:id', function(context) {
//            var id = this.params['id'];
//            context.log('Remove playlist with id ' + id);
//            removeFromPlaylist(id);
//        });

        this.get('#/allmusic/', function(context) {
            context.log('Getting allmusic');
            getSongs(defaultSorting, "", true);
        });
        
//        this.get('#/allmusic/addtoplaylist/:id', function(context) {
//            var id = this.params['id'];
//            context.log('add song to playlist with id ' + );
//        });

//        this.get('#/allmusic/removesong/:id', function(context) {
//            var id = this.params['id'];
//            context.log('Removing song with id ' + id);
//        });
        
//        this.get('#/uploadSong', function(context) {
//            context.log('Uploading');
//            $("#dialog-form").dialog("open");
//        });

        this.get('#/search/', function(context) {
            var search = this.params['search'];
            context.log('Searching content for: empty search');
            getSongs(defaultSorting, "", true);
        });

        this.get('#/search/:search', function(context) {
            var search = this.params['search'];
            context.log('Searching content for: ' + search);
            //if search == ""
            //getSongs(defaultSorting, "", true);
            getSongs(defaultSorting, search, true);
        });    
    });
      
    $(function() {
        app.run('#/');
    });

});

// Get song by id and call the function appendArtistData
function getSongByIdForArtist(id) {
    var Id = id;
    var dataFromRequest;
    var request = $.ajax({
        type: 'GET',
        dataType: 'json',
        url: '/api/music?id=' + Id
    });
    request.done(function (data) {
        appendArtistData(data);
    });
    request.fail(function (jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
}

// Append the artist data acquired from Guitarparty
function appendArtistData(the_data) {
    var API_KEY = "21e2e55e3f126e2b63becaaa3d4636690980dcf3";
    $.ajaxSetup({
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Guitarparty-Api-Key', API_KEY);
        }
    });
    var request = $.ajax({
        dataType: 'json',
        type: 'GET',
        url: 'http://api.guitarparty.com/v2/artists/?query=' + the_data.songArtist
    });
    request.done(function (data) {
        var isFound = false;
        $.each(data.objects, function (key, val) {
            if (the_data.songArtist == val.name) {
                isFound = true;
                var artistInfo = document.createElement("div");
                $(artistInfo).attr("id", "artistInfo-" + the_data.Id);
                var artistTitle = document.createElement("p");
                $(artistTitle).append(val.name);
                var artistBio = document.createElement("span");
                $(artistBio).append(val.bio);

                $(artistInfo).append(artistTitle);
                $(artistInfo).append(artistBio);
                $('#artistSpan-' + the_data.Id).append(artistInfo).hide().slideDown("fast");
            }
        });
        if (!isFound) {
            var artistInfo = document.createElement("div");
            $(artistInfo).attr("id", "artistInfo-" + the_data.Id);
            var artistTitle = document.createElement("p");
            $(artistTitle).append("There are no information about this artist.");
            $(artistInfo).append(artistTitle);
            $('#artistSpan-' + the_data.Id).append(artistInfo).hide().slideDown("fast");
        }
    });
    request.fail(function (jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
}

// Get song by id and call the function appendLyrics
function getSongByIdForLyrics(id) {
    var Id = id;
    var dataFromRequest;
    var request = $.ajax({
        type: 'GET',
        dataType: 'json',
        url: '/api/music?id=' + Id
    });
    request.done(function (data) {
        appendLyrics(data);
    });
    request.fail(function (jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
}

// Append the lyrics data acquired from Guitarparty
function appendLyrics(the_data) {
    var API_KEY = "21e2e55e3f126e2b63becaaa3d4636690980dcf3";
    $.ajaxSetup({
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Guitarparty-Api-Key', API_KEY);
        }
    });
    var request = $.ajax({
        dataType: 'json',
        type: 'GET',
        url: 'http://api.guitarparty.com/v2/songs/?query=' + the_data.songName
    });
    request.done(function (data) {
        var isFound = false;
        $.each(data.objects, function (key, val) {
            if (isFound == false && the_data.songName == val.title) {
                // I assume that the first song with the same name is the correct song
                isFound = true;
                var lyricsInfo = document.createElement("div");
                $(lyricsInfo).attr("id", "lyricsInfo-" + the_data.Id);
                var songTitle = document.createElement("p");
                $(songTitle).append(val.title);
                var lyrics = document.createElement("span");
                $(lyrics).append(val.body);

                $(lyricsInfo).append(songTitle);
                $(lyricsInfo).append(lyrics);

                $('#lyricsSpan-' + the_data.Id).append(lyricsInfo).hide().slideDown("fast");
            }
        });
        if (!isFound) {
            var lyricsInfo = document.createElement("div");
            $(lyricsInfo).attr("id", "lyricsInfo-" + the_data.Id);
            var songTitle = document.createElement("p");
            $(songTitle).append("There are no lyrics available for this song.");
            $(lyricsInfo).append(songTitle);

            $('#lyricsSpan-' + the_data.Id).append(lyricsInfo).hide().slideDown("fast");
        }
    });
    request.fail(function (jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
}

// Append dropdown list for adding song to playlist
function appendDropDownList(songId){
    $("#playListDropDown-"+ songId).remove();
    var playlistDropDown = document.createElement("select");
    $(playlistDropDown).attr("name", "playlistDropDown");
    $(playlistDropDown).attr("class", "playlistDropDown");
    $(playlistDropDown).attr("id", "playListDropDown-"+ songId);

    var defaultNothing = document.createElement("option");
    $(defaultNothing).attr("value", "");
    $(defaultNothing).append("**Select**");
    $(playlistDropDown).append(defaultNothing);
    
    var request = $.ajax({
        type: 'GET',
        dataType: 'json',
        url: '/api/playlist'
    });
    request.done(function (data) {
        for(var i = 0; i < data.length ; i++)
        {
           var option = document.createElement("option");
           $(option).attr("value", data[i].Id);
           $(option).append(data[i].PlaylistName);
           $(playlistDropDown).append(option);

        }
    });
    request.fail(function (jqXHR, textStatus) {
        alert("Request failed(getPlaylist): " + textStatus);
    });           

    $("#addPlaylistArea-" + songId).append(playlistDropDown);

}

// Add a song to a playlist
function addSongToPlayList(theId, thePlaylistId ){
    var newId = parseInt(theId);
    var nerPId = parseInt(thePlaylistId);
    var request = $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/api/playlist/',
        data: {songId : newId, playlistId: nerPId}
    });
    request.done(function () {
        //TODO maybe something, but not necessarily
    });
    request.fail(function (jqXHR, textStatus) {
        alert("Request failed(creating playlist): " + textStatus);
    });             
    
}

// Remove a playlist
function removeFromPlaylist(playlistId){
    var id = parseInt(playlistId);
    var request = $.ajax({
        type: 'DELETE',
        dataType: 'json',
       // data: {id : id}, 
        url: '/api/playlist?id=' + id,
    });
    request.done(function () {
        getPlaylists();
    });
    request.fail(function (jqXHR, textStatus) {
        alert("Request failed(RemovePlaylist): " + textStatus);
    });            
}

// Remove a song
function removeSong(songId){
    var id = parseInt(songId);
    var request = $.ajax({
        type: 'DELETE',
        dataType: 'json',
        //data: {id : songId}, 
        url: '/api/music?id=' + id,
        //url: '/api/music/'
    });
    request.done(function () {
        getSongs(selected,dataDisplayPhrase, true);
    });
    request.fail(function (jqXHR, textStatus) {
        alert("Request failed(RemoveSongs): " + textStatus);
    });            
}

// Get all the playlists
function getPlaylists() {
    //location.hash = "playlist";
    var request = $.ajax({
        type: 'GET',
        dataType: 'json',
        url: '/api/playlist'
    });
    request.done(function (data) {
        appendPlayLists(data);
    });
    request.fail(function (jqXHR, textStatus) {
        alert("Request failed(getPlaylist): " + textStatus);
    });           
}

// Append and render the playlist list/view
function appendPlayLists(data){
    $("#songInfo").empty();
    var createPlayListArea = document.createElement("div");
    $(createPlayListArea).attr("id", "createPlayListArea");
    var createPlayList = document.createElement("a");
    $(createPlayList).attr("id", "createPlaylist");
    $(createPlayList).attr("href", "#/playlist/");

    var img = document.createElement("img");
    $(img).attr("class", "removeLink");
    $(img).attr("src", "../../Content/Icons/icon_addlink.gif");
    $(img).attr("alt", "add-image");

    $(createPlayList).append("Create new playlist ");
    $(createPlayList).append(img);
    $(createPlayListArea).append(createPlayList);

    var createList = document.createElement("ul");
    $(createList).attr("id", "playlistRemoveList");

    for(var i = 0; i < data.length ; i++){
        var createItem = document.createElement("li");
        $(createItem).attr("id", "playlist-" + data[i].Id);
        //var playListName = document.createElement("span");
        var playListName = document.createElement("a");
        $(playListName).attr("class", "play");
        $(playListName).attr("id","playList-" + data[i].Id);
        $(playListName).attr("href","#/playlist/" + data[i].Id);
        $(playListName).append(data[i].PlaylistName);
        
        /*var removePlaylist = document.createElement("div");
        $(removePlaylist).attr("id", "removePlaylistArea-" + data[i].Id);
        $(removeSong).attr("class", "playlistLinks");*/
        var removeHref = document.createElement("a");
        $(removeHref).attr("class", "removePlaylist");
        $(removeHref).attr("id", "removePlaylist-" + data[i].Id);
        $(removeHref).attr("href", "#/playlist/");
        var img = document.createElement("img");
        $(img).attr("class", "removeLink");
        $(img).attr("src", "../../Content/Icons/icon_deletelink.gif");
        $(img).attr("alt", "remove-image");
        $(removeHref).append("Remove Playlist ");
        $(removeHref).append(img);
        //$(removePlaylist).append(removeHref);

        $(createItem).append(playListName);
        $(createItem).append(removeHref);
        $(createList).append(createItem);

    }
    $("#songInfo").append(createPlayListArea);
    $("#songInfo").append(createList);
}

// Load songs into music player for a playlist id
function playSongsFromPlaylist(playlistId){
    $("#emptyPlaylist-" + playlistId).remove();
     var request = $.ajax({
            type: 'GET',
            dataType: 'json',
           // data: {id : playlistId},
            url: '/api/playlist/'+ playlistId
        });
        request.done(function (data) {
            if(data.length != 0){
                //alert(data.length);
                //appendSongs(data);
                loadPlayer(data)
            }
            else{
                //alert(data.length);
                var empty = document.createElement("p");
                var empty2 = document.createElement("p");
                $(empty).attr("id","emptyPlaylist-"+ playlistId);
                $(empty).append("Playlist is empty!");
                $(empty2).append("You can add songs to your playlists by hitting the AddToPlaylist button under All Music.");
                $("#errorMessages").append(empty).append(empty2).hide().fadeIn("slow");
            }
        });
        request.fail(function (jqXHR, textStatus) {
            alert("Request failed(getSongs): " + textStatus);
        });
}

// Get all songs from collection by search and sort criteria
function getSongs(order, searchQuery, load) {
    if(searchQuery != ""){
        var request = $.ajax({
            type: 'GET',
            dataType: 'json',
            url: '/api/music?$orderby=' + order + ',' + defaultSorting,
            data: { search: searchQuery }
        });
        request.done(function (data) {
            if(data.length != 0){
                appendSongs(data, load);
            }
            else{
                $('#songInfo').empty();
                $('#musicPlayer').empty();
            }
        });
        request.fail(function (jqXHR, textStatus) {
            alert("Request failed(getSongs): " + textStatus);
        });
    }
    else{
        var request = $.ajax({
            type: 'GET',
            dataType: 'json',
            url: '/api/music?$orderby=' + order + ',' + defaultSorting
        });
        request.done(function (data) {
            if(data.length != 0){
                appendSongs(data, load);
            }
            else{
                $('#songInfo').empty();
                $('#musicPlayer').empty();
                var empty = document.createElement("p");
                var empty2 = document.createElement("p");
                $(empty).append("You music collection is empty!");
                $(empty2).append("You can add songs to your collection by hitting the Upload button.");
                $("#errorMessages").append(empty).append(empty2).hide().fadeIn("slow");
            }
        });
        request.fail(function (jqXHR, textStatus) {
            alert("Request failed(getSongs): " + textStatus);
        });        
    }
}

// Create and render view for a song collection and music player
function appendSongs(data, load){
    $('#songInfo').empty();
    var sortDropDown = document.createElement("select");
    $(sortDropDown).attr("name", "sortBy");
    $(sortDropDown).attr("id", "sortSongs");

    var optionTitle = document.createElement("option");
    $(optionTitle).attr("value", "songName");
    if(selected == "songName"){
        $(optionTitle).attr("selected", "true");
    }
    $(optionTitle).append("Title");

    var optionArtists = document.createElement("option");
    $(optionArtists).attr("value","songArtist");
    if(selected == "songArtist"){
        $(optionArtists).attr("selected", "true");
    }
    $(optionArtists).append("Artist");

    var optionGenre = document.createElement("option");
    $(optionGenre).attr("value", "songGenre");
    if(selected == "songGenre"){
        $(optionGenre).attr("selected", "true");
    }
    $(optionGenre).append("Genre");

    var playerSongsList = document.createElement("ul");
    $(playerSongsList).attr("id", "songList");
    $.each(data, function (key, val) {
        var songListItem = document.createElement("li");
        $(songListItem).attr("id", "song" + val.Id);

        //add to playlist div og a href
        var addToPlaylist = document.createElement("div");
        $(addToPlaylist).attr("id", "addPlaylistArea-" + val.Id);
        $(addToPlaylist).attr("class", "songLinks");
        var addHref = document.createElement("a");
        $(addHref).attr("class", "addToPlaylist");
        $(addHref).attr("id", "addSong-" + val.Id);
        $(addHref).attr("href", "#/allmusic/");
        
        var img = document.createElement("img");
        $(img).attr("class", "removeLink");
        $(img).attr("src", "../../Content/Icons/icon_addlink.gif");
        $(img).attr("alt", "add-image");
        $(addHref).append("Add To Playlist ");
        $(addHref).append(img);
        $(addToPlaylist).append(addHref);

        //remove song
        var removeSong = document.createElement("div");
        $(removeSong).attr("id", "removeArea-" + val.Id);
        $(removeSong).attr("class", "songLinks");
        var removeHref = document.createElement("a");
        $(removeHref).attr("class", "removeSong");
        $(removeHref).attr("id", "removeSong-" + val.Id);
        $(removeHref).attr("href", "#/allmusic/");
        var img2 = document.createElement("img");
        $(img2).attr("class", "removeLink");
        $(img2).attr("src", "../../Content/Icons/icon_deletelink.gif");
        $(img2).attr("alt", "remove-image");
        $(removeHref).append("Delete Song ");
        $(removeHref).append(img2);
        $(removeSong).append(removeHref);

        var songTitle = document.createElement("span");
        $(songTitle).append(" Title: " + val.songName);

        var songArtist = document.createElement("span");
        $(songArtist).append("Artist : " + val.songArtist);

        var songGenre = document.createElement("span");
        $(songGenre).append("Genre : " + val.songGenre);

        var showArtistInfo = document.createElement("span");
        $(showArtistInfo).attr("id", "artistSpan-" + val.Id);
        var artist = document.createElement("a");
        $(artist).attr("class", "artist");
        $(artist).attr("id", "artist-" + val.Id);
        $(artist).attr("href", "#/allmusic/");
        $(artist).append("Show Artist Info");
        $(showArtistInfo).append(artist);

        var showSongLyrics = document.createElement("span");
        $(showSongLyrics).attr("id", "lyricsSpan-" + val.Id);
        var lyrics = document.createElement("a");
        $(lyrics).attr("class", "lyrics");
        $(lyrics).attr("id", "lyrics-" + val.Id);
        $(lyrics).attr("href", "#/allmusic/");
        $(lyrics).append("Show Lyrics");
        $(showSongLyrics).append(lyrics);

        $(songListItem).append(addToPlaylist);
        $(songListItem).append(removeSong);
        $(songListItem).append(songTitle);
        $(songListItem).append(songArtist);
        $(songListItem).append(songGenre);
        $(songListItem).append(showArtistInfo);
        $(songListItem).append(showSongLyrics);

        $(playerSongsList).append(songListItem);

    });    
    $(sortDropDown).append(optionTitle);
    $(sortDropDown).append(optionArtists);
    $(sortDropDown).append(optionGenre);

    $('#songInfo').append(sortDropDown).hide().fadeIn(500);
    $('#songInfo').append(playerSongsList).hide().fadeIn(500);

    if(load == true){
        loadPlayer(data);
    }  
}

// Load data in player and display player
function loadPlayer(data) {
    $('#musicPlayer').empty();
        musicList = [];
        for (var i = 0; i < data.length; i++) {
            var obj = { src: data[i].songSource, name: data[i].songName + " - " + data[i].songArtist, length: data[i].songLength };
            musicList.push(obj);
        }
        var myOptions = { autoPlay: false,
            erroMessage: "This is the user custom error message",
            //albumCover: "../../Content/Music/IV/AlbumArtSmall.jpg",
            albumName: "Others",
            artistName: "Various"
        };

        $('#musicPlayer').musicPlayer(musicList, myOptions).hide().fadeIn(1500);
}

//function loadPlayer() {
//    $('#musicPlayer').empty();
//    //alert("Getting song");
//    $.getJSON("/api/music", function (data) {
//        //alert(data.songName + " " + data.songArtist + " " + data.songSource);

//        musicList = [];
//        for (var i = 0; i < data.length; i++) {
//            var obj = { src: data[i].songSource, name: data[i].songName + " - " + data[i].songArtist, length: data[i].songLength };
//            musicList.push(obj);
//        }
//        var myOptions = { autoPlay: false,
//            erroMessage: "This is the user custon error message",
//            //albumCover: "../../Content/Music/IV/AlbumArtSmall.jpg",
//            albumName: "Others",
//            artistName: "Various"
//        };

//        $('#musicPlayer').musicPlayer(musicList, myOptions).hide().fadeIn(1500);
//    });
//}